//引入对应得antd中得组件
import { Button, Card, Space, Table, Tag, Modal, Upload, UploadProps, message, Input, Form } from 'antd'
import React from 'react'
//引入请求
import { reqTrademarkReturnRecordsType, requestAddTrademark, requestDeleteTrademark, requestTrademarkList, requestUpdateTrademark } from "@/api/product/index"
import { useEffect, useState,useRef } from 'react'
import { PlusOutlined, FormOutlined, DeleteOutlined, LoadingOutlined } from "@ant-design/icons"
//引入类型
import { UploadChangeParam } from 'antd/lib/upload'
import { RcFile, UploadFile } from 'antd/lib/upload/interface'
const { Column, ColumnGroup } = Table;
export default function Trademark() {
    //声明当前页
    const [page, setPage] = useState(1)
    //声明一页几条数据
    const [limit, setLimit] = useState(3)
    //声明一共得数据
    const [total, setTotal] = useState(15)
    //声明点击当前数据的id
    const [currentId,setCurrentId] = useState(0)
    //弹窗声明数据
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [inputvalue,setInputvalue] = useState("")
    const baseUrl = process.env.REACT_APP_APIP;
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    //定义当前页面得商品列表数据
    const [trademarkList, setTrademarkList] = useState<reqTrademarkReturnRecordsType>([])
    //初始化得时候发送请求;当page和limit数据发生改变的时候，重新加载数据
    useEffect(() => {
        gettrademarkList()
    }, [page, limit])
    //1.请求商品列表数据
    const gettrademarkList = async () => {
        //传入当前页和一页展示几个
        const result = await requestTrademarkList({ page, limit })
        //设置属性
        console.log(result);
        setTrademarkList(result.records)
        //设置当前页和总条数
        setTrademarkList(result.records)
        //设置总页数
        setTotal(result.total)
    }
    //2.点击删除按钮之后发送请求
    const deletetrademarkList = async (id: number) => {
        //发送请求
        await requestDeleteTrademark(id)
        //更新数据
        gettrademarkList()
    }
    //3.点击添加或者修改 弹出弹窗
    const ThepopupWindows = (id?: number) => {
        //进页面首先判断是否带有id
        if (id) {
            console.log(id, "有id，是修改");
            //弹出窗口
            setIsModalOpen(true)
            //有id就数据回填
            const backtrademarkList =  trademarkList.filter(Item=>Item.id ===id)
            setInputvalue(backtrademarkList[0].tmName)
            setImageUrl(backtrademarkList[0].logoUrl)
            setCurrentId(backtrademarkList[0].id)
        } else {
            console.log("没有id是增加");
            setIsModalOpen(true)
            //让所有数据清空
            setImageUrl("");
            setInputvalue("")
            setCurrentId(0)
        }
    }
    //4.弹窗内input变化调用函数
    const inputChange =(e:any)=>{
        //设置input的值
        setInputvalue(e.target.value)
    }
    //5.点击确认保存事件
    const save =async ()=>{
        //首先让弹窗消失
        setIsModalOpen(false)
        if(currentId===0){
            //说明是增加事件
            const trademark ={
                tmName:inputvalue,
                logoUrl: imageUrl as string
            }
            await requestAddTrademark(trademark)
            //更新数据
            gettrademarkList()
        }else{
            //如果是有id说明 是修改
            const trademark ={
                id:currentId,
                tmName:inputvalue,
                logoUrl: imageUrl as string
            }
            await requestUpdateTrademark(trademark)
            //更新数据
            gettrademarkList()
        }

    }
    //弹窗的事件
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    //弹窗的事件
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
                setLoading(false);
                setImageUrl(info.file.response.data);
                // console.log(info.file.response.data);
        }
    };
    //弹窗的事件
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <Card>
            {/* 头部按钮 */}
            <Button type="primary" icon={<PlusOutlined />} onClick={() => ThepopupWindows()}>添加</Button>
            <br /> <br />
            {/* 中间表单 */}
            <Table dataSource={trademarkList}
                bordered
                rowKey="id"
                pagination={{
                    //页码的配置：当前页码
                    current: page,
                    //总数据的数量
                    total,
                    //每页条数
                    pageSize: limit,
                    //展示更改每页条数的选项(默认total大于50条的时候开启)
                    pageSizeOptions: [3, 8, 15],
                    //是否直接开启更新每页条数的选项
                    showSizeChanger: true,
                    showTotal(total) {
                        return `总共有15条数据`
                    },
                    //点击
                    onChange(page: number, limit: number) {
                        //page是 当前页；
                        setPage(page)
                        setLimit(limit)
                    }
                }}
            >
                <Column title="序号" key="id" render={(text, record, index) => {
                    return index + 1
                }} />
                <Column title="品牌名称" dataIndex="tmName" key="tmName" />
                <Column title="品牌LOGO" dataIndex="logoUrl" key="logoUrl"
                    render={(logoUrl) => {
                        return (<img src={logoUrl} height={100}></img>)
                    }}
                />
                <Column title="操作" dataIndex="tags" key="tags"
                    render={(_, data: any) => {
                        return (
                            <div>
                                <Button type="primary" icon={<FormOutlined />} onClick={() => ThepopupWindows(data.id)} >修改</Button>
                                <Button type="link" icon={<DeleteOutlined />} onClick={() => deletetrademarkList(data.id)}>删除</Button>
                            </div>
                        )
                    }}
                />
            </Table>

            {/* 弹框 */}
            <Modal title="品牌管理" visible={isModalOpen} onOk={save} onCancel={() => setIsModalOpen(false)}>
                <Form >
                    <Form.Item label="品牌名称">
                        <Input  onChange={inputChange}   value={inputvalue}/>
                    </Form.Item >
                    <Form.Item  label="品牌LOGO" >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action={`${baseUrl}/admin/product/upload`}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal>
        </Card>
    )
}


